"""
Author        yongfa
Date          2022-07-06 14:24:33
LastEditTime  2023-08-31 03:51:35
LastEditors   yongfa
Description   常用方法
"""

import decimal
import hashlib
import base64
import hmac
import json
import uuid
import random
import string
from datetime import datetime, timedelta

from flask import current_app
from flask_restx import reqparse


def get_uuid() -> str:
    """生成uuid"""
    return uuid.uuid4().hex


def get_random_str(length: int = 16) -> str:
    """生成随机数"""
    return ''.join(random.sample(string.ascii_letters + string.digits, length))


def get_datetime(strftime="%Y-%m-%d %H:%M:%S", **kwargs):
    """ 参考timedelta

    Args:
        days (int, optional): _description_. Defaults to 0.
        seconds (int, optional): _description_. Defaults to 0.
        microseconds (int, optional): _description_. Defaults to 0.
        milliseconds (int, optional): _description_. Defaults to 0.
        minutes (int, optional): _description_. Defaults to 0.
        hours (int, optional): _description_. Defaults to 0.
        weeks (int, optional): _description_. Defaults to 0.
    """
    _time = datetime.now()
    if kwargs:
        _time = _time + timedelta(**kwargs)
    return _time.strftime(strftime)


def md5sum(src: str) -> str:
    m = hashlib.md5()
    m.update(src.encode('utf-8'))
    return m.hexdigest()


def get_hmac_sha256(data, key):
    key = key.encode('utf-8')
    message = data.encode('utf-8')
    sign = base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest())
    sign = str(sign, 'utf-8')
    return sign


def get_sha1(str):
    sha = hashlib.sha1(str.encode('utf-8'))
    encrypts = sha.hexdigest()
    return encrypts.upper()


def token_key(user_id: int, user_type: str = 'user') -> str:
    # 缓存key user_ + user_id
    key = user_type + '_' + str(user_id)
    return key


def paginate() -> tuple:
    """
    获取分页查询的参数
    :return: page第几页；size每页数据的规模
    """
    page_args = reqparse.RequestParser()
    page_args.add_argument('page', type=int, default=current_app.config.get('PAGE'))
    page_args.add_argument('size', type=int, choices=range(1, 101), default=current_app.config.get('PAGE_SIZE'))

    args = page_args.parse_args()
    page = args.get('page')
    size = args.get('size')

    return page, size


def fHideMid(str, count=4, fix='*'):
    """
       #隐藏/脱敏 中间几位
       str 字符串
       count 隐藏位数
       fix 替换符号
    """
    if not str:
        return ''
    count = int(count)
    str_len = len(str)
    ret_str = ''
    if str_len == 1:
        return str
    elif str_len == 2:
        ret_str = str[0] + '*'
    elif count == 1:
        mid_pos = int(str_len / 2)
        ret_str = str[:mid_pos] + fix + str[mid_pos + 1:]
    else:
        if str_len - 2 > count:
            if count % 2 == 0:
                if str_len % 2 == 0:
                    ret_str = str[:int(str_len / 2 - count / 2)] + count * fix + str[int(str_len / 2 + count / 2):]
                else:
                    ret_str = str[:int((str_len + 1) / 2 - count / 2)] + count * \
                        fix + str[int((str_len + 1) / 2 + count / 2):]
            else:
                if str_len % 2 == 0:
                    ret_str = str[:int(str_len / 2 - (count - 1) / 2)] + count * \
                        fix + str[int(str_len / 2 + (count + 1) / 2):]
                else:
                    ret_str = str[:int((str_len + 1) / 2 - (count + 1) / 2)] + count * \
                        fix + str[int((str_len + 1) / 2 + (count - 1) / 2):]
        else:
            ret_str = str[0] + fix * (str_len - 2) + str[-1]

    return ret_str
